package com.rsscollector.util;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;
import java.util.Vector;

/**
 * Created by IntelliJ IDEA.
 * User: Vu Nga
 * Date: Sep 8, 2007
 * Time: 3:22:23 PM
 * To change this template use File | Settings | File Templates.
 */
public class SendMailJob implements Job {
    private static Logger logger = Logger.getLogger(SystemUtils.class.getName());

    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        logger.info("Start send email ...");
        long startDate = System.currentTimeMillis();
        Properties properties = null;
        MimeMessage msg = null;
        try {
            // Read properties file.
            ClassLoader cl = SendMailJob.class.getClassLoader();
            InputStream is = cl.getResourceAsStream("/mail.properties");
            properties = new Properties();
            properties.load(is);
            is.close();

            // Get the default Session using Properties Object
            Session session = Session.getDefaultInstance(properties, null);
            session.setDebug("true".equals(properties.getProperty("mail.debug")) ? true : false); // Enable the debug mode
            // Create a New message
            msg = new MimeMessage(session);
            // Set the From address
            msg.setFrom(new InternetAddress(properties.getProperty("mail.from")));
            // Setting the "Cc recipients" addresses
            //msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(p_cc, false));
            // Setting the "BCc recipients" addresses
            //msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(p_bcc, false));
            msg.setSubject(properties.getProperty("mail.subject")); //Sets the Subject
            // Create and fill the first message part
            MimeBodyPart html = new MimeBodyPart();
            html.setContent(IO.readTextFile(properties.getProperty("mail.body.file")), properties.getProperty("mail.body.type"));
//			   MimeBodyPart text = new MimeBodyPart();
//			  text.setText("message")

				// Create the Multipart and its parts to it
            Multipart mp = new MimeMultipart("alternative");
            mp.addBodyPart(html);

            // Add the Multipart to the message
            msg.setContent(mp);

            // Set the Date: header
            msg.setSentDate(new Date());
        } catch (IOException e) {
            e.printStackTrace();
        }//end catch block
        catch (MessagingException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        String files[] = properties.getProperty("mail.to.file").split(";");
        Vector mailTo = null;
        StringBuffer listEmailNotSent = new StringBuffer();
        // read each file that contain list email
        for (int i = 0; i < files.length; i++) {
            try {
                mailTo = IO.readEmailFile(files[i]);
            } catch (IOException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
            for (int j = 0; j < mailTo.size(); j++) {
                String mail = (String) mailTo.get(j);
                // Setting the "To recipients" addresses
                try {
                    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(mail, false));
                    // Send the message
                    Transport.send(msg);
                } catch (MessagingException e) {
                    listEmailNotSent.append(mail).append(";");
                    logger.error(e.getMessage());
                }
            }
        }

        long endDate = System.currentTimeMillis();
        // If here, then message is successfully sent.
        try {
            IO.writeTextFile(properties.getProperty("mail.notsent"), listEmailNotSent.toString());
        } catch (IOException e1) {
        }
        try {
            IO.writeTextFile(properties.getProperty("mail.report"), "Time send mail: "+((endDate - startDate)/3600000));
        } catch (IOException e1) {
        }
        logger.info("End send email ...");
    }

}
